package com.github.pig.training.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.model.entity.SysDict;
import com.github.pig.admin.service.SysDictService;
import com.github.pig.admin.service.SysUserService;
import com.github.pig.common.bean.interceptor.DataScope;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.vo.UserVO;
import com.github.pig.sales.entity.SalesCollarHis;
import com.github.pig.sales.entity.SalesIntentionFlowup;
import com.github.pig.sales.entity.SalesPublicRepertory;
import com.github.pig.sales.mapper.SalesIntentionFlowupMapper;
import com.github.pig.sales.service.ISalesCollarHisService;
import com.github.pig.sales.service.ISalesIntentionFlowupService;
import com.github.pig.sales.service.ISalesPublicRepertoryService;
import com.github.pig.sales.service.impl.SalesCollarHisServiceImpl;
import com.github.pig.training.entity.TrainingStudent;
import com.github.pig.training.mapper.TrainingStudentMapper;
import com.github.pig.training.service.ITrainingStudentService;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.models.auth.In;
import org.apache.poi.util.StringUtil;
import org.reflections.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.github.pig.common.util.Query;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 学员信息 服务实现类
 * </p>
 *
 * @author andrew
 * @since 2018-06-16
 */
@Service
@Transactional
public class TrainingStudentServiceImpl extends ServiceImpl<TrainingStudentMapper, TrainingStudent> implements ITrainingStudentService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDictService dictService;
    @Autowired
    private TrainingStudentMapper trainingStudentMapper;
    @Autowired
    private ITrainingStudentService iTrainingStudentService;
    @Autowired
    private ISalesPublicRepertoryService publicRepertoryService;

    @Autowired
    private ISalesIntentionFlowupService flowupService;

    @Autowired
    private SysUserService userService;
    @Autowired
    private ISalesCollarHisService iSalesCollarHisService;
    @Autowired
    private SalesIntentionFlowupMapper salesIntentionFlowupMapper;
    @Autowired
    private ISalesIntentionFlowupService iSalesIntentionFlowupService;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public R<Boolean> sFollowUp(int sid, String userName) {
        //获取用户id
        int uid = sysUserService.findUserByUsername(userName).getUserId();
        //当前用户是否能领取
        int count = salesIntentionFlowupMapper.getFlagById(uid);
        //判断跟进率是否合格
        int rate = salesIntentionFlowupMapper.getRateById(uid);
        if( rate == 0 ){
            return new R<>(Boolean.FALSE, "领取人跟进率未达标!");
        }
        if (count >= 0) {
            //查询学员信息
            EntityWrapper<TrainingStudent> ew = new EntityWrapper<>();
            ew.where("fid={0}", sid);
            TrainingStudent student = iTrainingStudentService.selectOne(ew);
            //修学员信息
//            student.setCallCount(student.getCallCount()+1);
            student.setUpdateUser(uid);
            student.setUpdateTime(new Date());
            student.setFollowUpStatus("1601");
            student.setFollowUpUser(uid);
//            student
            student.setCallCount(0);
            iTrainingStudentService.updateById(student);
            salesIntentionFlowupMapper.sFollowUp(sid);
            //添加意向跟进
//            SalesIntentionFlowup salesIntentionFlowup = new SalesIntentionFlowup();
//            salesIntentionFlowup.setStudentId(sid);
//            salesIntentionFlowup.setCreateUser(uid);
//            salesIntentionFlowup.setCreateTime(new Date());
//            salesIntentionFlowup.setUpdateTime(new Date());
//            salesIntentionFlowup.setIntentionLevel(student.getIntentionLevel());
//            salesIntentionFlowup.setBizStatus("1");
//            salesIntentionFlowup.setDelFlag(CommonConstant.STATUS_NORMAL);
//            iSalesIntentionFlowupService.insert(salesIntentionFlowup);
            //添加领用记录
            SalesCollarHis salesCollarHis = new SalesCollarHis();
            salesCollarHis.setBizStatus("1");
            salesCollarHis.setCreateDate(new Date());
            salesCollarHis.setDelFlag(CommonConstant.STATUS_NORMAL);
            salesCollarHis.setUserId(uid);
            salesCollarHis.setStudentId(sid);
            salesCollarHis.setUpdateTime(new Date());
            iSalesCollarHisService.insert(salesCollarHis);
            return new R<>(Boolean.TRUE,"");
        } else {
            return new R<>(Boolean.FALSE, "领取人领取人数已达上限!");
        }
    }

    /**
     * 跟进
     * 杨北平   2018-06-26
     *
     * @param obj
     * @param user
     * @return
     */
    public R<Boolean> addFlowup(Object obj,UserVO user) {
        Map<String, Object> map = (HashMap) obj;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //得到系统规定最大跟进次数
        SalesPublicRepertory publicRepertory = this.publicRepertoryService.selectList(new EntityWrapper<>()).get(0);
        TrainingStudent trainingStudent = new TrainingStudent();
        SalesIntentionFlowup flowup = new SalesIntentionFlowup();
        trainingStudent.setFid(Integer.valueOf(map.get("fid").toString()));
        Object object = map.get("groupsort");
        if (object != null) {
            if (StringUtils.isEmpty(object.toString())) {
                trainingStudent.setGroupsort(Integer.valueOf(map.get("groupsort").toString()));
            }
        }
        Integer currentCallCount = Integer.valueOf(map.get("currentCallCount").toString());
        if (map.get("followUpStatus").toString().equals("1601")||map.get("followUpStatus").toString().equals("1603")) {
            trainingStudent.setDelFlag(CommonConstant.STATUS_NORMAL);
            //当跟进次数已达到最大次数
            if ((currentCallCount + 1) >= publicRepertory.getMaxCallNum() && map.get("followUpStatus").toString().equals("1601")) {
                trainingStudent.setCallCount(currentCallCount+1);// 总跟进次数加1
                trainingStudent.setCurrentCallCount(0);  //  当前跟进次数清零
                trainingStudent.setIntentionLevel("");
                trainingStudent.setFollowUpStatus("1602"); //  将跟进状态设置为未跟进
                trainingStudent.setFollowUpUser(-1);//将跟进人置空
                flowup.setRemark(map.get("remark").toString() + "==>已达到最大跟进次数");
            } else {
                //跟进次数未达到最大跟进次数
                trainingStudent.setCallCount(currentCallCount+1);// 总跟进次数加1
                trainingStudent.setCurrentCallCount(currentCallCount + 1); //  当前跟进次数加1
                trainingStudent.setIntentionLevel(map.get("intentionLevel").toString());
                trainingStudent.setLastFollowUpTime(new Date());
                trainingStudent.setFollowUpStatus(map.get("followUpStatus").toString());
                String nextFollowUpDate = map.get("nextFollowUpDate").toString();
                try {
                    trainingStudent.setNextFollowUpDate(sdf.parse(nextFollowUpDate));
                }catch (ParseException e){
                    e.printStackTrace();
                }
                flowup.setIntentionLevel(map.get("intentionLevel").toString());
                flowup.setRemark(map.get("remark").toString());
                Calendar ca = Calendar.getInstance();
                ca.setTime(new Date());
                ca.add(Calendar.DATE,1);
                String lastDate =sdf.format(ca.getTime()).toString().substring(0,10);
                if ((currentCallCount + 2) >= publicRepertory.getMaxCallNum()){
                    trainingStudent.setWarningType(1);
                }else if(lastDate.equals(nextFollowUpDate.substring(0,10))){
                    trainingStudent.setWarningType(2);
                }else{
                    trainingStudent.setWarningType(0);
                }
            }
        }else{
            trainingStudent.setCurrentCallCount(0);  //  当前跟进次数清零
            trainingStudent.setIntentionLevel("");
            trainingStudent.setFollowUpStatus("1602"); //  将跟进状态设置为未跟进
            trainingStudent.setFollowUpUser(-1);//将跟进人置空
            flowup.setRemark(map.get("remark").toString());
        }
        UserVO sysUser = userService.findUserByUsername(user.getUsername());  //查询当前用户信息
        flowup.setStudentId(new Integer(map.get("fid").toString()));
        flowup.setCreateUser(sysUser.getUserId());
        flowup.setCreateTime(new Date());
        flowup.setUpdateTime(new Date());
        flowup.setDeptId(sysUser.getDeptId());
        flowup.setDelFlag(CommonConstant.STATUS_NORMAL);
        return new R<>(super.updateById(trainingStudent)&&flowupService.insert(flowup));
    }

    /**
     *
     * 定时检查跟进天数是否大于最大天数
     *
     */
    @Override
    public void checkDayNum() {
        Integer maxDayNum = this.publicRepertoryService.selectList(new EntityWrapper<>()).get(0).getMaxDayNum();
        List<TrainingStudent> studentList = trainingStudentMapper.checkDayNum(maxDayNum);
        SalesIntentionFlowup flowup = new SalesIntentionFlowup();
        for (TrainingStudent student:studentList){
            student.setFollowUpStatus("1602");
            student.setCurrentCallCount(0);
            student.setIntentionLevel("");
            student.setFollowUpUser(-1);
            student.setWarningType(0);
            flowup.setStudentId(student.getFid());
            flowup.setCreateTime(new Date());
            flowup.setUpdateTime(new Date());
            flowup.setDelFlag(CommonConstant.STATUS_NORMAL);
            trainingStudentMapper.updateById(student);
            flowupService.insert(flowup);
        }
        studentList.clear();
        studentList = trainingStudentMapper.checkDayNum(maxDayNum-1);
        for (TrainingStudent student:studentList){
            student.setWarningType(1);
            trainingStudentMapper.updateById(student);
        }
    }

    /**
     * 修改学生状态
     * @param id
     * @param state
     * @return
     */
    public R<Boolean> updState(int id ,int state){
        Map map = new HashMap();
        map.put("id",id);
        map.put("state",state);
        return new R<>(trainingStudentMapper.updState(map)==1);
    }

    /**
     * 效验学生信息
     */
    public R<Boolean> checkInformation(String str){
        EntityWrapper<TrainingStudent> nw = new EntityWrapper<>();
        TrainingStudent t = null;
        if(str.length()>=15){
            nw.where("id_card={0}",str);
            t = selectOne(nw);
        }else{
            nw.where("tel1={0}",str);
            t = selectOne(nw);
            if(t==null){
                nw.where("tel2={0}",str);
                t = selectOne(nw);
            }
        }
        if(t!=null){
            return new R<>(false,""+t.getFid());
        }else{
            return new R<>(true,"");
        }
    }

    public Page selectWithRolePage(Query query,int userId,String condition){
        return query.setRecords(trainingStudentMapper.selectStudentByCondition(query, userId,condition));
    }

    /**
     * 多选条件查询通用
     * @param map
     * @return
     */
    public EntityWrapper<TrainingStudent> getEwByCondition(Map<String,Object> map){

        //需要多选查询的字段
        String[] condition = { "label", "intention_level", "working_area" };

        EntityWrapper wrapper = new EntityWrapper(new TrainingStudent());
        wrapper.where(CommonConstant.DEL_FLAG + "={0}", CommonConstant.STATUS_NORMAL).and("(follow_up_status = '1601' or follow_up_status = '1603')")
                .and("follow_up_user = {0}", map.get("userId")).orderBy("last_follow_up_time", true);
        map.remove("userId");

        //姓名电话号码查询
        if(map!=null&&map.get("condition")!=null&&map.get("condition").toString().length()>0){
            wrapper.and("( fname like '%"+ map.get("condition").toString() +"%' "+
                    "OR tel1 like '%"+ map.get("condition").toString() +"%' "+
                    "OR tel2 like '%"+ map.get("condition").toString() +"%')");
            map.remove("condition"); }

        //多选查询条件
        Map<String,Object> map1 = com.github.pig.training.util.Query.getEntityWrapperByCondition(wrapper,map);
        wrapper = (EntityWrapper) map1.get("entityWrapper");
        map = (Map<String,Object>) map1.get("map");
//        for(String str : condition){
//            if(map!=null&&map.get(str)!=null&&map.get(str).toString().length()>0){
//                String[] strs=map.get(str).toString().split(",");
//                String sql = "(";
//                for(int i = 0,len = strs.length; i<len;i++){
//                    sql += str + " like '%" + strs[i] +"%' OR "; }
//                sql = sql.substring(0,(sql.length()-3));
//                wrapper.and(sql+")");
//                map.remove(str);
//            }
//        }
        return wrapper;
    }
}
